import { useRef } from 'react';

const depsAreSame = (oldDeps: any[], currDeps: any[]) => {
  if (oldDeps === currDeps) return true;
  for (const idx in oldDeps) {
    if (!Object.is(oldDeps[idx], currDeps[idx])) return false;
  }
  return true;
};
const isFunction = (fn: any) => fn instanceof Function;
export default function useCreation(initValue: any, deps: any[]) {
  // 每次渲染useRef返回值都不变；
  const { current } = useRef({
    deps,
    value: undefined,
    initialized: false,
  });

  if (current.initialized === false || !depsAreSame(current.deps, deps)) {
    current.deps = deps;
    current.value = isFunction(initValue) ? initValue() : initValue;
    current.initialized = true;
  }
  return current.value;
}
